
<style >
  .me-top{
    padding-top: 20px;
  }
  #menuBox .el-dialog__body{
    display: inline-block;
  }
</style>
<template>
  <el-container class="me-top">
    <el-header>
      <el-row>
        <el-col :span="18" style="text-align: left;">
          <el-form ref="form" :model="formInline" :inline="true">
            <el-form-item label="名称:">
              <el-input v-model="formInline.name" />
            </el-form-item>

            <el-button icon="el-icon-search" circle @click="search" />
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="add">添加</el-button>
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确认全部删除？"
            @onConfirm="BatchRemove"
          >
            <el-button slot="reference" :disabled="flag" type="danger">批量删除</el-button>
          </el-popconfirm>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table :data="tableData" border stripe style="width: 100%" @selection-change="selectedRows">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column prop="name" label="角色名称" align="center" />
        <el-table-column prop="sn" label="角色描述" align="center" />
        <el-table-column prop="permission" label="角色权限" align="center" >
          <template slot-scope="scope">
            <el-tag v-for=" item in scope.row.permission" style="margin-right: 5px;">
                {{item.name}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="menus" label="角色菜单" align="center" >
          <template slot-scope="scope">
<!--            <i class="el-icon-key" @click="openMenuBox(scope.row)">添加菜单</i>-->
            <el-tag v-for=" item in scope.row.menus" style="margin-right: 5px;">
              {{item.name}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center"  width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit-outline" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="你确定要删除当前数据？"
              @onConfirm="remove(scope.row)"
            >
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- :current-page="2"-->
      </div>
    </el-main>
    <!--<el-dialog title="菜单信息" :visible.sync="menuInfoBox" center id="menuBox">
      <el-transfer :titles = "['所有菜单','拥有菜单']" @change="ChangedMenu" v-model="menuValue" :props="{ key: 'id', label: 'name'  }" :data="menuData"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuInfoBox = false">取 消</el-button>
        <el-button type="primary" @click="submitMenuInfo">确 定</el-button>
      </div>
    </el-dialog>-->
    <!--  新增、编辑-->
    <el-dialog title="新增用户" center width="40%" :visible.sync="dialogFormVisible">
      <el-form ref="addForm"  :model="addForm" label-width="100px" status-icon :rules="rules" >
        <input v-model="addForm.id" type="hidden">
        <el-form-item prop="name"  label="角色名称:"  style="width: 66%">
          <el-input v-model="addForm.name"  />
        </el-form-item>
        <el-form-item prop="sn" label="角色描述:">
          <el-input v-model="addForm.sn"  type="textarea" :rows="3" style="width: 60%" />
        </el-form-item>
        <el-transfer
          filterable
          :titles = "['所有权限','拥有权限']"
          :props="{ key: 'id', label: 'name' }"
          @change="ChangedPermission"
          filter-placeholder="请输入关键字"
          v-model="addForm.permission"
          :data="permissionData" style="padding-left: 28px;">
        </el-transfer>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
export default {
  data() {
    return {
      // rowRoleId : '',//当前行 角色id
      // menuValue :[],
      menuInfoBox : false,
      flag: true,
      addForm: {
        id: '',
        name: '',
        sn: '',
        permission:[]
      },
      page: 1, // 第几页
      size: 10, // 每页条数
      total: 0,
      pageSizes: [5, 10, 15, 20],
      tableData: [],
      formInline: {
        name: '',
        date: ''
      },
      dialogFormVisible: false,
      selectRows: {},
      permissionData :[], //穿梭框数据
      checkedPermission : [], //穿梭框选中的的数据数据
      // menuData : []
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadListData()
    this.findAllPermission()
    // this.findAllMenu()
  },
  methods: {
   /* submitMenuInfo(){
      this.$http.post('/role/roleMenuUpdate',{id:this.rowRoleId,ManyIds:this.menuValue}).then(res => {
        this.menuData = res.data.data
        this.loadListData()
        this.$notify({ title: '成功',  message: res.data.message + '，修改拥有菜单！',  type: 'success' });
      }).catch(error => {
        this.$notify({ title: '失败',  message: error.message + '，请刷新后在操作！',  type: 'warning' });
      })
      this.menuInfoBox = false
    },
    openMenuBox(row){
      this.menuValue = []
      this.rowRoleId = row.id
      row.menus.forEach(item => {
        this.menuValue.push(item.id)
      });
      this.menuInfoBox = true
    },
    ChangedMenu(value){
      this.menuValue = value
      console.log(value)
    },
    findAllMenu(){
      this.$http.get('/menu/findAll').then(res => {
        this.menuData = res.data.data
      })
    },*/
    ChangedPermission(value){
      this.checkedPermission = value
      console.log(this.checkedPermission)
    },
    findAllPermission(){
      this.$http.get('/permission/findAll').then(res => {
        this.permissionData = res.data.data
      })
    },
    search() {
      this.loadListData()
    },
    submit() {
      const axios = this.$http //定义请求
      let check = this.checkedPermission
      let param = this.addForm
      let temp = []
      for (let i = 0; i < check.length; i++) {
        temp.push({"id":check[i]})
      }
      param.permission = temp
      if (param.id) { // 修改
        axios.put('/role/update', param).then((res) => {
          if (res.data.success) {
            this.$notify({ title: '成功',  message: res.data.message + '修改一条记录！',  type: 'success' });
            this.loadListData()
            this.dialogFormVisible = false
        } else {
          this.$notify({ title: '修改失败',  message: error.message ,  type: 'warning' });
        }
        }).catch(error => {
          console.log(error)
        })
      } else { // 添加
        const axios = this.$http //定义请求
        const msg= this.$message //定义消息弹框
        axios.post('/role/insert',param).then((res) => {
          if (res.data.success) {
            this.$notify({ title: '成功',  message: res.data.message + '添加一条记录！',  type: 'success' });
            this.loadListData()
            this.dialogFormVisible = false
          } else {
            this.$notify({ title: '添加失败',  message: error.message ,  type: 'warning' });
          }
         }).catch(error => {
          console.log(error)
         })
      }
    },
    add() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
        this.addForm.permission = []
      })
      for(let key in this.addForm){
        this.addForm[key] = ''
      }
    },
    edit(row) {
      this.dialogFormVisible = true
      this.checkedPermission = []
      let permission = row.permission
      permission.forEach(item =>{
        this.checkedPermission.push(item.id)
      })
      this.$nextTick(() => {
        this.addForm = Object.assign({}, row)
        this.addForm.permission = this.checkedPermission
      })
    },
    remove(row) {
      let axios = this.$http //定义请求
      let msg= this.$message //定义消息弹框
      axios.delete('/role/deleteById/' + row.id).then(res => {
        this.$notify({ title: '删除成功',  message: res.data.message + '删除一条记录！',  type: 'success' });
        this.loadListData()
      }).catch(error => {
        this.$notify({ title: '删除失败',  message: res.data.message + ',请刷新后在操作！！',  type: 'warning' });
      })
    },
    BatchRemove() {
      let axios = this.$http //定义请求
      let msg= this.$message //定义消息弹框
      const ids = this.selectRows.map(function(obj, index, arr) {
        return obj.id
      })
      console.log(ids.toString())
      axios.post('/role/batchDeleteByIds', { ids: ids }).then(res => {
        this.$notify({ title: '删除成功',  message: res.data.message + '删除'+res.data.affectCount +'条记录！',  type: 'success' });
        this.loadListData()
      }).catch(error => {
        msg.error('删除失败[' + error.message + ']')
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.loadListData()
    },
    handleCurrentChange(currentPage) {
      this.page = currentPage
      this.loadListData()
    },
    loadListData() {
      let axios = this.$http //定义请求
      this.loading = true
      // vue加载完成，发送ajax请求动态获取数据
      const param = {
        'pageNo': this.page,
        'pageSize': this.size,
        'keyWord': this.formInline.name
      }
      axios.post('/role/findForList', param).then((res) => {
        this.tableData = res.data.data.result
        this.total = res.data.data.total
        this.page = res.data.data.pageNo
        }).catch(error => {
        console.log(error)
})
    },
    selectedRows(rows) {
      console.log(rows)
      if (rows.length > 0) {
        this.flag = false
        this.selectRows = rows
      } else {
        this.flag = true
      }
    }
  }
}
</script>

